import com.lucastex.grails.fileuploader.UFile
import grails.converters.JSON

class CoursewareAjaxController {

     // 上传处理页面
    def upload = {
        log.info "Uploaded file with id=${params.ufile}"
         
        if (flash.message) { 
            log.info "${flash.message}"
            render(text:"{'success': false, 'message':  '${flash.message}'}")
        }else{
            def ufile = UFile.get(params.ufileId.toLong())
            log.info "{'success': true, 'message':  {'id':${ufile.id} , 'name':${ufile.name} , 'size':${ufile.size} }}"
            render(text:"{'success': true, 'message':  {'id':'${ufile.id}' , 'name':'${ufile.name}' , 'size':'${ufile.size}' }}")
        }
    }
// 显示、下载图片是报错后，默认的方法
    def show = {
        
    }

    def deleteAttachment = {
        log.info "articleAjax.deleteAttachment params.id = ${params.id}"
        def ufile = UFile.get(params.id)
        if (ufile) {
            try {
                def article = Article.get(params.articleId)
                if (article) {
                    article.removeFromAttachments(ufile)
                    article.save(flush: true) 
                }
 
                ufile.delete(flush: true)

                new File(ufile.path).delete() 
                return render(['success': true ,'message' : '删除成功。'] as JSON) 

            }
            catch (Exception e) {
                log.info "articleAjax.deleteAttachment Exception"
                 return render(['success': false ,'message' : '删除失败。'] as JSON) 
            }
        }else{
            log.info "articleAjax.deleteAttachment 没找到"
             return render(['success': false ,'message' : '没找到这个附件。'] as JSON) 
        }
    }
}
